package com.chaoyong.higo.fragment;


import org.apache.http.entity.StringEntity;
import org.json.JSONObject;

import com.chaoyong.higo.R;
import com.chaoyong.higo.activity.GetedGoodsActivity;
import com.chaoyong.higo.activity.LoginActivity;
import com.chaoyong.higo.activity.MyAccountActivity;
import com.chaoyong.higo.activity.MySettingsActivity;
import com.chaoyong.higo.activity.MyYunBActivity;
import com.chaoyong.higo.activity.OrderManagerActivity;
import com.chaoyong.higo.activity.PersonalDataActivity;
import com.chaoyong.higo.activity.PurchaseRecordActivity;
import com.chaoyong.higo.adapter.MyPurchaseAdapter;
import com.chaoyong.higo.base.BaseFragment;
import com.chaoyong.higo.bean.FragAccountBean;
import com.chaoyong.higo.bean.PersonInfoBean;
import com.chaoyong.higo.fragment.FragHomePage.SetClickListener;
import com.chaoyong.higo.net.OApi;
import com.chaoyong.higo.utils.EmptyUtil;
import com.chaoyong.higo.utils.JLog;
import com.chaoyong.higo.utils.PrefUtils;
import com.chaoyong.higo.utils.Values;
import com.chaoyong.higo.view.RoundImageView;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.nostra13.universalimageloader.core.ImageLoader;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * 我的云筹
 * 
 * @author zk
 *
 */
public class FragMyPurchase extends BaseFragment implements OnItemClickListener, OnClickListener {

	private static final String ClassName = FragMyPurchase.class.getName();

	// title部分
	private RelativeLayout title_right_sort;
	private ImageView title_right_img;
	private TextView title_center_text;

	// 页面布局
	private ListView purchase_list_view;
	private MyPurchaseAdapter adapter;

	/** 头像 */
	private RoundImageView iv_accountpic;
	/** hello */
	private TextView tv_name;// hello,问候语噻
	/** 手机号 */
	private TextView tv_tel;
	/** 等级 */
	private TextView tv_degree;
	/** 查看等级 */
	private TextView tv_empirical1;
	/** 可用余额布局 */
	private LinearLayout header_yu_e;
	/** 可用云币布局 */
	private LinearLayout header_yun_bi;
	/** 可用余额 */
	private TextView tv_counts;
	/** 可用云币 */
	private TextView tv_yun_bi;
	String account_amount;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		mView = inflater.inflate(R.layout.frag_my_purchase, container, false);
		return mView;
	}

	@Override
	public void findView() {
		title_right_sort = (RelativeLayout) mView.findViewById(R.id.title_right_sort);
		title_right_img = (ImageView) mView.findViewById(R.id.title_right_img);
		title_center_text = (TextView) mView.findViewById(R.id.title_center_text);
		purchase_list_view = (ListView) mView.findViewById(R.id.purchase_list_view);

		if(PrefUtils.getBoolean(mContext, "isLogin", false)){
			title_right_img.setVisibility(View.VISIBLE);
			// 个人信息，包括头像、等级、余额、云币
			RelativeLayout hearderViewLayout = (RelativeLayout) LayoutInflater.from(getActivity())
					.inflate(R.layout.frag_my_item_header, null);
			purchase_list_view.addHeaderView(hearderViewLayout);
			
			iv_accountpic = (RoundImageView) mView.findViewById(R.id.iv_accountpic);
			tv_name = (TextView) mView.findViewById(R.id.tv_name);
			tv_tel = (TextView) mView.findViewById(R.id.tv_tel);
			tv_degree = (TextView) mView.findViewById(R.id.tv_degree);
			tv_empirical1 = (TextView) mView.findViewById(R.id.tv_empirical1);
			header_yu_e = (LinearLayout) mView.findViewById(R.id.header_yu_e);
			header_yun_bi = (LinearLayout) mView.findViewById(R.id.header_yun_bi);
			tv_counts = (TextView) mView.findViewById(R.id.tv_counts);
			tv_yun_bi = (TextView) mView.findViewById(R.id.tv_yun_bi);
			
			iv_accountpic.setOnClickListener(this);
			tv_empirical1.setOnClickListener(this);
			//header_yu_e.setOnClickListener(this);
			//header_yun_bi.setOnClickListener(this);
		}else{
			title_right_img.setVisibility(View.GONE);
			RelativeLayout hearderViewLayout = (RelativeLayout) LayoutInflater.from(getActivity())
					.inflate(R.layout.frag_my_item_header_nologin, null);
			purchase_list_view.addHeaderView(hearderViewLayout);
			Button btn = (Button) mView.findViewById(R.id.nologin_login_btn);
			btn.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Intent intent = new Intent(mContext, LoginActivity.class);
					mContext.startActivity(intent);
					((Activity) mContext).overridePendingTransition(R.anim.slide_in_from_bottom, R.anim.slide_out_to_top); 
				}
			});
		}
	}

	@Override
	public void init() {
		title_right_sort.setVisibility(View.GONE);
		//title_right_img.setVisibility(View.VISIBLE);
		title_center_text.setText("我的夺宝");

		adapter = new MyPurchaseAdapter(mContext);
		purchase_list_view.setAdapter(adapter);

		purchase_list_view.setOnItemClickListener(this);
		title_right_img.setOnClickListener(this);
		
		
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		switch (arg2) {
		// 此处listview添加了header，所以item记录位置从1开始，
		case 1:
			// showToast("云筹记录");
			if(PrefUtils.getBoolean(mContext, "isLogin", false) == false){
				Intent intent = new Intent(mContext, LoginActivity.class);
				startActivity(intent);
				((Activity) mContext).overridePendingTransition(R.anim.slide_in_from_bottom, R.anim.slide_out_to_top); 
			}else{
				startActivity(new Intent(mContext, PurchaseRecordActivity.class));
			}
			break;
		case 2:
			// showToast("获得商品");
			if(PrefUtils.getBoolean(mContext, "isLogin", false) == false){
				Intent intent = new Intent(mContext, LoginActivity.class);
				startActivity(intent);
				((Activity) mContext).overridePendingTransition(R.anim.slide_in_from_bottom, R.anim.slide_out_to_top); 
			}else{
				startActivity(new Intent(mContext, GetedGoodsActivity.class));
			}
			break;
		case 3:
			// showToast("晒单管理");
			if(PrefUtils.getBoolean(mContext, "isLogin", false) == false){
				Intent intent = new Intent(mContext, LoginActivity.class);
				startActivity(intent);
				((Activity) mContext).overridePendingTransition(R.anim.slide_in_from_bottom, R.anim.slide_out_to_top); 
			}else{
				startActivity(new Intent(mContext, OrderManagerActivity.class));
			}
			break;
		case 4:
			// showToast("我的账户");
			if(PrefUtils.getBoolean(mContext, "isLogin", false) == false){
				Intent intent = new Intent(mContext, LoginActivity.class);
				startActivity(intent);
				((Activity) mContext).overridePendingTransition(R.anim.slide_in_from_bottom, R.anim.slide_out_to_top); 
			}else{
				Intent i = new Intent(mContext, MyAccountActivity.class);
				i.putExtra("account_amount", account_amount);
				startActivity(i);
			}
			break;
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_right_img:// 设置
			startActivity(new Intent(mContext, MySettingsActivity.class));
			break;
		case R.id.iv_accountpic:// 头像
			// showToast("头像");
			startActivity(new Intent(mContext, PersonalDataActivity.class));
			break;
		case R.id.tv_empirical1:// 查看等级
			showToast("查看等级");
			break;
		case R.id.header_yu_e:// 可用余额布局
			showToast("可用余额");
			break;
		case R.id.header_yun_bi:// 可用云币布局
			// showToast("可用云币");
			startActivity(new Intent(mContext, MyYunBActivity.class));
			break;
		}
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		String uid = PrefUtils.getString(mContext, "userId", "1");
		boolean b = PrefUtils.getBoolean(mContext, "isLogin", false);
		if(PrefUtils.getBoolean(mContext, "isLogin", false) == true){
			httpQueryPersonInfo(uid);
			// httpQueryPersonInfo("1");
			httpQueryAccountInfo(uid);
		}
		 
		 /*if(PrefUtils.getBoolean(mContext, "isLogin", false)){
				RelativeLayout hearderViewLayout = (RelativeLayout) LayoutInflater.from(getActivity())
						.inflate(R.layout.frag_my_item_header, null);
				purchase_list_view.addHeaderView(hearderViewLayout);

				iv_accountpic = (RoundImageView) mView.findViewById(R.id.iv_accountpic);
				tv_name = (TextView) mView.findViewById(R.id.tv_name);
				tv_tel = (TextView) mView.findViewById(R.id.tv_tel);
				tv_degree = (TextView) mView.findViewById(R.id.tv_degree);
				tv_empirical1 = (TextView) mView.findViewById(R.id.tv_empirical1);
				header_yu_e = (LinearLayout) mView.findViewById(R.id.header_yu_e);
				header_yun_bi = (LinearLayout) mView.findViewById(R.id.header_yun_bi);
				tv_counts = (TextView) mView.findViewById(R.id.tv_counts);
				tv_yun_bi = (TextView) mView.findViewById(R.id.tv_yun_bi);
				
				String uid = PrefUtils.getString(mContext, "userId", "1");
				
				
				httpQueryPersonInfo(uid);
				// httpQueryPersonInfo("1");
				 httpQueryAccountInfo(uid);
			}else{
				RelativeLayout hearderViewLayout = (RelativeLayout) LayoutInflater.from(getActivity())
						.inflate(R.layout.frag_my_item_header_nologin, null);
				purchase_list_view.addHeaderView(hearderViewLayout);
			}*/
	}

	/**
	 * 用户账户信息
	 */
	private void httpQueryAccountInfo(String uid) {
		HttpUtils utils = new HttpUtils();
		final RequestParams param = new RequestParams();
		try {
			JSONObject jsonObject = new JSONObject();
			JSONObject info = new JSONObject();

			jsonObject.putOpt("model", "Members");
			jsonObject.putOpt("function", "showInfoApp");
			jsonObject.putOpt("info", info);

			info.putOpt("uid", uid);

			param.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		utils.send(HttpMethod.POST, OApi.Appport_appMember, param, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				JLog.i(ClassName, arg0.getMessage() + "\n" + "上传数据："+param.toString());
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				JLog.i(ClassName, arg0.result);
				Gson gson = new Gson();
				FragAccountBean bean = gson.fromJson(arg0.result, FragAccountBean.class);
				String status = bean.getStatus();
				if (status.equals("1")) {
					FragAccountBean.DataEntity entities = bean.getData();
					if (entities != null) {
						setAccountData(entities);
					}
				}
			}
		});
	}

	private void setAccountData(FragAccountBean.DataEntity entities) {
		String user_name = entities.getUser_name();
		account_amount = entities.getAccount_amount();
		String yunbi = entities.getYunbi();


		PrefUtils.setString(mContext, "dear_name", user_name);
		if (!EmptyUtil.isEmpty(user_name)) {
			tv_tel.setText(user_name + "");
		} else {
			tv_tel.setText("");
		}
		
		if (!EmptyUtil.isEmpty(account_amount)) {
			tv_counts.setText("￥" + account_amount);
			PrefUtils.setString(mContext, "yue", account_amount);
		} else {
			tv_counts.setText("￥0.00");
		}
		
		if (!EmptyUtil.isEmpty(yunbi)) {
			tv_yun_bi.setText(yunbi + "");
			PrefUtils.setString(mContext, "yunbi", yunbi);
		} else {
			tv_yun_bi.setText("0");
		}
	}

	/**
	 * 只是为了获取头像
	 * 
	 * @param uid
	 */
	private void httpQueryPersonInfo(String uid) {
		HttpUtils utils = new HttpUtils();
		RequestParams param = new RequestParams();
		try {
			JSONObject jsonObject = new JSONObject();
			JSONObject info = new JSONObject();

			jsonObject.putOpt("model", "MemberInfo");
			jsonObject.putOpt("function", "index");
			jsonObject.putOpt("info", info);

			info.putOpt("uid", uid);

			param.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		utils.send(HttpMethod.POST, OApi.Appport_appMember, param, new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				JLog.i(ClassName, arg0.getMessage());
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				String result = arg0.result;
				Gson gson = new Gson();
				PersonInfoBean bean = gson.fromJson(result, PersonInfoBean.class);
				String status = bean.getStatus();
				if (status.equals("1")) {
					PersonInfoBean.DataEntity entities = bean.getData();
					if (entities != null) {
						setDatas(entities);
					}
				}
			}
		});
	}

	private void setDatas(PersonInfoBean.DataEntity entities) {
		// 头像
		String uid_portrait = (String) entities.getUid_portrait();
		String dear_name = entities.getDear_name();
		
		//PrefUtils.setString(mContext, "dear_name", dear_name);
		
		/*if (!EmptyUtil.isEmpty(dear_name)) {
			tv_tel.setText(dear_name + "");
		} else {
			tv_tel.setText(entities.getPhone());
		}*/

		if (!EmptyUtil.isEmpty(uid_portrait)) {
			ImageLoader.getInstance().displayImage(Values.BASE_IMAGE_URL + uid_portrait, iv_accountpic);
			// bitmapUtils.display(data_.head_img, Values.BASE_IMAGE_URL +
			// uid_portrait);
		} else {
			// bitmapUtils.display(data_head_img, "drawable://"+
			// R.drawable.head_image);
			ImageLoader.getInstance().displayImage("drawable://" + R.drawable.head_image, iv_accountpic);
		}

	}
	
	public void refresh(){
		if (getActivity() instanceof SetClickListener) {
			((SetClickListener) getActivity()).onShopsClick();
		}
	}
}
